package fussbudget.abstracts;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;

import fussbudget.gui.TransactionTablePanel.TransactionTableModel;
import fussbudget.gui.components.BasicPopupMenu;
import fussbudget.gui.components.HasPopupMenu;
import fussbudget.gui.components.support.TablePanelRenderer;

public class AbstractTablePanelWithPopup<E> extends JPanel implements HasPopupMenu {
	public Container		parent;

	public AbstractTableWithPopup	table	= new AbstractTableWithPopup();
	public JScrollPane		scroll;
	public BasicPopupMenu	popup;

	public AbstractTablePanelWithPopup(String name, Container parent) {
		super();

		this.parent = parent;

		setBorder(new TitledBorder(name));

		table = new AbstractTableWithPopup(5, 3);
		table.setFillsViewportHeight(true);
		// table.setModel(new PaymentEntityTableModel());
		table.setDefaultRenderer(Object.class, new TablePanelRenderer());
		// table.setDefaultEditor(DateMidnight.class, new DateCellEditor());

		scroll = new JScrollPane(table);
		// scroll.setPreferredSize(new Dimension(200, 250));
		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

		add(scroll);

		setupPopup();
	}

	@Override
	public void setupPopup() {
		ArrayList<HasPopupMenu> haveMenu = new ArrayList<HasPopupMenu>();
		haveMenu.add(this);
		haveMenu.add(table);
		// haveMenu.add((TableHeaderWithPopup)table.getTableHeader());

		popup = new BasicPopupMenu(haveMenu);
		popup.addMenuItem("Add", new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("Add new Transaction...");
				//((TransactionTableModel) table.getModel()).addRow(new Transaction("NEW TRANSACTION"));
			}
		});
		/*
		 * popup.addMenuItem("Edit", new ActionListener() {
		 * @Override
		 * public void actionPerformed(ActionEvent arg0) {
		 * System.out.println("Edit Transaction...");
		 * }
		 * });
		 */
		popup.addMenuItem("Delete", new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("Delete Transaction...");
				int whichRow = table.getSelectedRow();
				((TransactionTableModel) table.getModel()).removeRow(whichRow);// .addRow(new Transaction("NEW TRANSACTION"));
				table.revalidate();
				table.repaint();
			}
		});
	}

	public void setModel(AbstractTableModel model) {
		table.setModel(model);
	}

	@Override
	public BasicPopupMenu getPopup() {
		return popup;
	}

	@Override
	public void setPopup(BasicPopupMenu newPopup) {
		this.popup = newPopup;
	}
}
